package com.ruoyi.web.controller.module.event;

import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.*;

import cn.hutool.core.util.StrUtil;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.utils.PageUtils;
import com.ruoyi.system.domain.module.estate.Estate;
import com.ruoyi.system.domain.module.event.*;
import com.ruoyi.system.domain.module.property.Property;
import com.ruoyi.system.service.module.estate.IEstateService;
import com.ruoyi.system.service.module.event.*;
import com.ruoyi.system.service.module.property.IPropertyService;
import com.ruoyi.system.service.system.ISysUserService;
import com.ruoyi.web.controller.common.BaseController;
import lombok.RequiredArgsConstructor;
import javax.validation.constraints.*;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.validation.annotation.Validated;
import com.ruoyi.common.annotation.RepeatSubmit;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.validate.AddGroup;
import com.ruoyi.common.core.validate.EditGroup;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;

/**
 * 巡检巡更、保洁等 执行计划Controller
 *
 * @author ruoyi
 * @date 2023-12-25
 */
@Validated
@Api(value = "巡检巡更、保洁等 执行计划控制器", tags = {"巡检巡更、保洁等 执行计划管理"})
@RequiredArgsConstructor(onConstructor_ = @Autowired)
@RestController
@RequestMapping("/module/event/plan")
public class EventPlanController extends BaseController {

    private final IEventPlanService eventPlanService;
	private final IEventPlanTaskService eventPlanTaskService;
	private final ISysUserService sysUserService;
	private final IEventPlanWorkService eventPlanWorkService;
	private final IPropertyService propertyService;
	private final IEstateService estateService;
	private final IEventPlanTaskLeaderService eventPlanTaskLeaderService;
	private final IEventPlanTaskInfoService eventPlanTaskInfoService;
	private final IEventTerminalsService eventTerminalsService;
	private final IEventPatrolPointService eventPatrolPointService;
	private final IEventPatrolLineInfoService eventPatrolLineInfoService;
	private final IEventTerminalGroupService eventTerminalGroupService;
	private final IEventPatrolLineService eventPatrolLineService;
	private final IEventCleanAreaListService eventCleanAreaListService;

	/**
     * 查询巡检巡更、保洁等 执行计划列表
     */
    @ApiOperation("查询巡检巡更、保洁等 执行计划列表")
    @PreAuthorize("@ss.hasPermi('module:eventPlan:list')")
    @GetMapping("/list")
    public TableDataInfo<EventPlan> list(@Validated EventPlan eventPlan) {
		SysUser sysUser = getUser();
		QueryWrapper<EventPlan> qw = new QueryWrapper<>();
		//用户类型 0 - 系统管理员  1 - 平台管理员 2 - 物业管理员  3 - 小区管理员
		if(sysUser.getUserType() == 2){
			qw.eq("property_id",sysUser.getPropertyId());
			if (sysUser.getEstateId()!=null){
				qw.eq("estate_id",sysUser.getEstateId());
			}
		} else if(sysUser.getUserType() == 3){
			qw.eq("estate_id",sysUser.getEstateId());
		}else{
			if(eventPlan.getPropertyId() != null){
				qw.eq("property_id",eventPlan.getPropertyId());
			}
			if(eventPlan.getEstateId() != null){
				qw.eq("estate_id",eventPlan.getEstateId());
			}
		}
		if(eventPlan.getEventTypeId()!=null){
			qw.eq("event_type_id",eventPlan.getEventTypeId());
		}
		if (eventPlan.getState()!=null){
			qw.eq("state",2);
		}
		if (eventPlan.getIsDel()!=null){
			qw.eq("is_del",eventPlan.getIsDel());
		}
		qw.orderByAsc("sort");
        TableDataInfo<EventPlan> td = PageUtils.buildDataInfo(eventPlanService.page(PageUtils.buildPage(),qw));
        List<EventPlan> list = td.getRows();

		for (EventPlan plan : list){
			plan.setLoading(true);
//			QueryWrapper<EventPlanWork> qw1 = new QueryWrapper<>();
//			if (plan.getId()!=null){
//				qw1.eq("event_plan_id",plan.getId());
//			}
//			LocalDateTime dateTime = LocalDateTime.now().plusDays(1);
//			qw1.between("begin_time", "2023-01-01 00:00:00",dateTime);
//			qw1.orderByDesc("begin_time");
//			List<EventPlanWork> list2 = eventPlanWorkService.list(qw1);
//			for (EventPlanWork list1:list2){
//				if (list1.getWorkerSysUserId()!=null){
//					SysUser user = sysUserService.selectUserById(list1.getWorkerSysUserId());
//					if (user!=null){
//						list1.setNickName(user.getNickName());
//					}
//				}else {
//					list1.setNickName("未执行");
//				}
//				if (list1.getPropertyId()!=null){
//					Property property = propertyService.findById(list1.getPropertyId());
//					if (property!=null){
//						list1.setPropertyName(property.getPropertyName());
//					}
//				}
//				if (list1.getEstateId()!=null){
//					Estate estate = estateService.findById(list1.getEstateId());
//					if (estate!=null){
//						list1.setEstateName(estate.getEstateName());
//					}
//				}
//				list1.setPlanName(plan.getPlanTitle());
//				if (list1.getOpResult()==null){
//					list1.setOpResult("暂无");
//				}
//				QueryWrapper<EventPlanTask> qwTask = new QueryWrapper<>();
//				qwTask.eq("work_id",list1.getId());
//				qwTask.ne("state",4);
//				List<EventPlanTask> taskList = eventPlanTaskService.list(qwTask);
//				if (taskList.size()>0){
//					String name = "";
//					for (EventPlanTask task:taskList){
//						if (name == ""){
//							name = task.getWorkerName();
//						}else {
//							name = name+","+ task.getWorkerName();
//						}
//					}
//					list1.setWorkerSysUserName(name);
//				}
//			}
//			plan.setWorkList(list2);
//
//			QueryWrapper<EventPlanWork> qw2 = new QueryWrapper<>();
//			if (plan.getId()!=null){
//				qw2.eq("event_plan_id",plan.getId());
//			}
//			List<EventPlanWork> list3 = eventPlanWorkService.list(qw2);
//			QueryWrapper<EventPlanWork> qw3 = new QueryWrapper<>();
//			if (plan.getId()!=null){
//				qw3.eq("event_plan_id",plan.getId());
//			}
//			qw3.eq("state",2);
//			List<EventPlanWork> list4 = eventPlanWorkService.list(qw3);
//			Double wancheng = Double.valueOf(list4.size());
//			Double all = Double.valueOf(list3.size());
//			Double bili = 0.00;
//			if (all == 0){
//				 bili = 0.00;
//			}else {
//				 bili = (wancheng/all)*100;
//			}
//			DecimalFormat df = new DecimalFormat("#0.00");
//			plan.setPercentage(df.format(bili));
		}
        return td;
    }
    /**
     * 导出巡检巡更、保洁等 执行计划列表
     */
    @ApiOperation("导出巡检巡更、保洁等 执行计划列表")
    @PreAuthorize("@ss.hasPermi('module:eventPlan:export')")
    @Log(title = "巡检巡更、保洁等 执行计划", businessType = BusinessType.EXPORT)
    @GetMapping("/export")
    public AjaxResult<EventPlan> export(@Validated EventPlan eventPlan) {
//        List<EventPlan> list = eventPlanService.list();
		SysUser sysUser = getUser();
		QueryWrapper<EventPlan> qw = new QueryWrapper<>();
		//用户类型 0 - 系统管理员  1 - 平台管理员 2 - 物业管理员  3 - 小区管理员
		if(sysUser.getUserType() == 2){
			qw.eq("property_id",sysUser.getPropertyId());
			if (sysUser.getEstateId()!=null){
				qw.eq("estate_id",sysUser.getEstateId());
			}
		} else if(sysUser.getUserType() == 3){
			qw.eq("estate_id",sysUser.getEstateId());
		}else{
			if(eventPlan.getPropertyId() != null){
				qw.eq("property_id",eventPlan.getPropertyId());
			}
			if(eventPlan.getEstateId() != null){
				qw.eq("estate_id",eventPlan.getEstateId());
			}
		}
		if(eventPlan.getEventTypeId()!=null){
			qw.eq("event_type_id",eventPlan.getEventTypeId());
		}
		if (eventPlan.getState()!=null){
			qw.eq("state",2);
		}
		if (eventPlan.getIsDel()!=null){
			qw.eq("is_del",eventPlan.getIsDel());
		}
		qw.orderByAsc("sort");
		TableDataInfo<EventPlan> td = PageUtils.buildDataInfo(eventPlanService.page(PageUtils.buildPage(),qw));
		List<EventPlan> list = td.getRows();

		ExcelUtil<EventPlan> util = new ExcelUtil<EventPlan>(EventPlan.class);
        return util.exportExcel(list, "巡检巡更、保洁等 执行计划");
    }
    /**
     * 获取巡检巡更、保洁等 执行计划详细信息
     */
    @ApiOperation("获取巡检巡更、保洁等 执行计划详细信息")
    @PreAuthorize("@ss.hasPermi('module:eventPlan:query')")
    @GetMapping("/{id}")
    public AjaxResult<EventPlan> getInfo(@NotNull(message = "主键不能为空") @PathVariable("id") Integer id) {
        EventPlan eventPlan = eventPlanService.getById(id);
		if (eventPlan.getCycleType().equals("day")){}else {
			if (eventPlan.getCycleDays()!=null){
				eventPlan.setCycleDay(Arrays.asList(eventPlan.getCycleDays().split(",")));
			}
		}
		EventPlanTaskLeader leader = eventPlanTaskLeaderService.selectByUniqueColumn("event_plan_id",eventPlan.getId());
		if (leader!=null){
			eventPlan.setLeaderId(leader.getLeaderSysUserId());
		}
		List<String> time = new ArrayList<>();
		Calendar calendar = Calendar.getInstance();
		calendar.setTime(eventPlan.getBeginTime());
		String beginTime = calendar.get(Calendar.YEAR)+"-"+calendar.get(Calendar.MONTH)+1+"-"+calendar.get(Calendar.DATE);
		calendar.setTime(eventPlan.getEndTime());
		String endTime = calendar.get(Calendar.YEAR)+"-"+calendar.get(Calendar.MONTH)+1+"-"+calendar.get(Calendar.DATE);
		time.add(beginTime);
		time.add(endTime);
		eventPlan.setDateRange(time);
		List<EventPlanInfo> infoList = new ArrayList<>();
		//基于计划id查询，事项分组
		QueryWrapper<EventPlanTask> qw = new QueryWrapper<>();
		qw.eq("event_plan_id",eventPlan.getId());
		qw.eq("event_type",eventPlan.getEventTypeId());
		qw.groupBy("event_target_id","task_begin_time","task_end_time");
		List<EventPlanTask> plans = eventPlanTaskService.list(qw);
		for (EventPlanTask plan : plans){
			EventPlanInfo info = new EventPlanInfo();
			info.setGroupId(plan.getEventTargetId());
			Calendar calendar1 = Calendar.getInstance();
			calendar1.setTime(plan.getBeginTime());
			String beginHour = "";
			String endHour = "";
			String beginMin = "";
			String endMin = "";
			if (calendar1.get(Calendar.HOUR_OF_DAY)<10){
				beginHour="0"+calendar1.get(Calendar.HOUR_OF_DAY);
			}else {
				beginHour= String.valueOf(calendar1.get(Calendar.HOUR_OF_DAY));
			}
			if (calendar1.get(Calendar.MINUTE)<10){
				beginMin="0"+calendar1.get(Calendar.MINUTE);
			}else {
				beginMin= String.valueOf(calendar1.get(Calendar.MINUTE));
			}
			info.setBeginRangeTime(beginHour+":"+beginMin);
			Calendar calendar2 = Calendar.getInstance();
			calendar2.setTime(plan.getEndTime());
			if (calendar2.get(Calendar.HOUR_OF_DAY)<10){
				endHour="0"+calendar2.get(Calendar.HOUR_OF_DAY);
			}else {
				endHour= String.valueOf(calendar2.get(Calendar.HOUR_OF_DAY));
			}
			if (calendar2.get(Calendar.MINUTE)<10){
				endMin="0"+calendar2.get(Calendar.MINUTE);
			}else {
				endMin= String.valueOf(calendar2.get(Calendar.MINUTE));
			}
			info.setEndRangeTime(endHour+":"+endMin);
			infoList.add(info);
		}
		//基于事项id查询，人员分组
		for (EventPlanInfo info :infoList){
			List<Integer> userId = new ArrayList<>();
			List<String> userName = new ArrayList<>();
			QueryWrapper<EventPlanTask> qw1 = new QueryWrapper<>();
			qw1.eq("event_plan_id",eventPlan.getId());
			qw1.eq("event_target_id",info.getGroupId());
			qw1.eq("event_type",eventPlan.getEventTypeId());
			qw1.eq("task_begin_time",info.getBeginRangeTime());
			qw1.eq("task_end_time",info.getEndRangeTime());
			qw1.eq("state",0);
			qw1.groupBy("worker_sys_user_id");
			List<EventPlanTask> tasks = eventPlanTaskService.list(qw1);
			for (EventPlanTask task : tasks){
				EventPlanWork work = eventPlanWorkService.findById(task.getWorkId());
				if (work!=null){
					info.setFinishType(work.getFinishType());
				}
				userId.add(task.getWorkerSysUserId());
				if (task.getWorkerSysUserId()!=null){
					SysUser user = sysUserService.selectUserById(Long.valueOf(task.getWorkerSysUserId()));
					if(user!=null){
						userName.add(user.getNickName());
					}
				}

			}
			info.setUserIds(userId.toArray(new Integer[0]));
			info.setUserName(userName.toArray(new String[0]));
			info.setPlanId(eventPlan.getId());
		}
		eventPlan.setEventPlanInfos(infoList.toArray(new EventPlanInfo[0]));


		QueryWrapper<EventPlanWork> qw1 = new QueryWrapper<>();
		if (eventPlan.getId()!=null){
			qw1.eq("event_plan_id", eventPlan.getId());
		}
		LocalDateTime dateTime = LocalDateTime.now().plusDays(1);
		qw1.between("begin_time", "2023-01-01 00:00:00",dateTime);
		qw1.orderByDesc("begin_time");
		List<EventPlanWork> list2 = eventPlanWorkService.list(qw1);
		for (EventPlanWork list1:list2){
			if (list1.getWorkerSysUserId()!=null){
				SysUser user = sysUserService.selectUserById(list1.getWorkerSysUserId());
				if (user!=null){
					list1.setNickName(user.getNickName());
				}
			}else {
				list1.setNickName("未执行");
			}
			if (list1.getPropertyId()!=null){
				Property property = propertyService.findById(list1.getPropertyId());
				if (property!=null){
					list1.setPropertyName(property.getPropertyName());
				}
			}
			if (list1.getEstateId()!=null){
				Estate estate = estateService.findById(list1.getEstateId());
				if (estate!=null){
					list1.setEstateName(estate.getEstateName());
				}
			}
			if (eventPlan.getEventTypeId() == 1){//巡检
				EventTerminalGroup group = eventTerminalGroupService.findById(list1.getEventTargetId());
				if (group!=null){
					list1.setEventTargetName(group.getGroupName());
				}
			}
			if (eventPlan.getEventTypeId() == 2){//巡更
				EventPatrolLine line = eventPatrolLineService.findById(list1.getEventTargetId());
				if (line!=null){
					list1.setEventTargetName(line.getLineName());
				}
			}
			if (eventPlan.getEventTypeId() == 3){//保洁
				EventCleanAreaList list = eventCleanAreaListService.findById(list1.getEventTargetId());
				if (list!=null){
					list1.setEventTargetName(list.getAreaName());
				}
			}
			if (eventPlan.getEventTypeId() == 4){//绿化
				EventCleanAreaList list = eventCleanAreaListService.findById(list1.getEventTargetId());
				if (list!=null){
					list1.setEventTargetName(list.getAreaName());
				}
			}
			if (eventPlan.getEventTypeId() == 5){//消杀
				EventCleanAreaList list = eventCleanAreaListService.findById(list1.getEventTargetId());
				if (list!=null){
					list1.setEventTargetName(list.getAreaName());
				}
			}
			if (eventPlan.getEventTypeId() == 6){//维保
				EventTerminalGroup group = eventTerminalGroupService.findById(list1.getEventTargetId());
				if (group!=null){
					list1.setEventTargetName(group.getGroupName());
				}
			}
			list1.setPlanName(eventPlan.getPlanTitle());
			if (list1.getOpResult()==null){
				list1.setOpResult("暂无");
			}
			QueryWrapper<EventPlanTask> qwTask = new QueryWrapper<>();
			qwTask.eq("work_id",list1.getId());
			qwTask.ne("state",4);
			List<EventPlanTask> taskList = eventPlanTaskService.list(qwTask);
			if (taskList.size()>0){
				String name = "";
				for (EventPlanTask task:taskList){
					if (name == ""){
						name = task.getWorkerName();
					}else {
						name = name+","+ task.getWorkerName();
					}
				}
				list1.setWorkerSysUserName(name);
			}
		}
		eventPlan.setWorkList(list2);
		eventPlan.setLoading(false);
		return AjaxResult.success(eventPlan);
    }


	/**
	 * 删除某人的 巡检巡更、保洁等 执行计划
	 */
	@ApiOperation("删除某人的巡检巡更、保洁等 执行计划")
	@PreAuthorize("@ss.hasPermi('module:eventPlan:add')")
	@Log(title = "巡检巡更、保洁等 执行计划", businessType = BusinessType.INSERT)
	@RepeatSubmit
	@PostMapping("/delectWorkUser")
	public Boolean delectWorkUser(@Validated(AddGroup.class) @RequestBody EventPlanInfo eventPlanInfo) {
		Boolean br = true;
		QueryWrapper<EventPlanTask> qw = new QueryWrapper<>();
		qw.eq("event_plan_id",eventPlanInfo.getPlanId());
		qw.eq("event_target_id",eventPlanInfo.getGroupId());
		qw.eq("task_begin_time",eventPlanInfo.getBeginRangeTime());
		qw.eq("task_end_time",eventPlanInfo.getEndRangeTime());
		qw.eq("worker_sys_user_id",eventPlanInfo.getDelectUserId());
		qw.eq("state",0);
		List<EventPlanTask> tasks = eventPlanTaskService.list(qw);
		for (EventPlanTask task:tasks){
			task.setState(4);
			br = eventPlanTaskService.updateById(task);
		}
		return br;
	}


	/**
	 * 新增 某人的 巡检巡更、保洁等 执行计划
	 */
	@ApiOperation("新增巡检巡更、保洁等 执行计划的人员")
	@PreAuthorize("@ss.hasPermi('module:eventPlan:add')")
	@Log(title = "巡检巡更、保洁等 执行计划", businessType = BusinessType.INSERT)
	@RepeatSubmit
	@PostMapping("/newWorkUser")
	public AjaxResult<Void> newWorkUser(@Validated(AddGroup.class) @RequestBody EventPlan eventPlan) {
		EventPlan plan = eventPlanService.getById(eventPlan.getId());
		int ret = 0;
		for (Integer userId :eventPlan.getUserIds()){
			plan.setUserId(userId);
			plan.setGroupId(eventPlan.getGroupId());
			plan.setBeginRangeTime(eventPlan.getBeginRangeTime());
			plan.setEndRangeTime(eventPlan.getEndRangeTime());
			plan.setIsDel(0);
			ret = eventPlanService.addUserWork(plan);
			if (ret == 0){
				break;
			}
		}
		return toAjax(ret);
	}

    /**
     * 新增巡检巡更、保洁等 执行计划
     */
    @ApiOperation("新增巡检巡更、保洁等 执行计划")
    @PreAuthorize("@ss.hasPermi('module:eventPlan:add')")
    @Log(title = "巡检巡更、保洁等 执行计划", businessType = BusinessType.INSERT)
    @RepeatSubmit
    @PostMapping()
    public AjaxResult<Void> add(@Validated(AddGroup.class) @RequestBody EventPlan eventPlan) {
		eventPlan.setIsDel(0);
		int ret = eventPlanService.addPlan(eventPlan);
		return toAjax(ret);
	}

    /**
     * 修改巡检巡更、保洁等 执行计划
     */
    @ApiOperation("修改巡检巡更、保洁等 执行计划")
    @PreAuthorize("@ss.hasPermi('module:eventPlan:edit')")
    @Log(title = "巡检巡更、保洁等 执行计划", businessType = BusinessType.UPDATE)
    @RepeatSubmit
    @PutMapping()
    public AjaxResult<Void> edit(@Validated(EditGroup.class) @RequestBody EventPlan eventPlan) {

		int ret = eventPlanService.editPlan(eventPlan);

		return toAjax(ret);
    }

	/**
	 * 夜间计划处理
	 */
	@ApiOperation("夜间计划处理")
	@PreAuthorize("@ss.hasPermi('module:eventPlan:query')")
	@GetMapping("/night/{id}")
	public Boolean night(@NotNull(message = "主键不能为空") @PathVariable("id") Integer id) {
		//处理task
		//查询结果
		boolean b = false;
		QueryWrapper<EventPlanTask> qw = new QueryWrapper<>();
		qw.eq("event_plan_id",id);
		List<EventPlanTask> tasks = eventPlanTaskService.list(qw);
		//处理数据
		for (EventPlanTask task:tasks){
			//判断该计划是否已经为夜间
			ZoneId zoneId = ZoneId.systemDefault();
			LocalDate begin = task.getBeginTime().toInstant().atZone(zoneId).toLocalDate();
			LocalDate end = task.getEndTime().toInstant().atZone(zoneId).toLocalDate();
			b = begin.isEqual(end);
			if (b == false){
				continue;
			}

			Calendar calendar = Calendar.getInstance(); // 获取当前日期
			calendar.setTime(task.getEndTime());
			calendar.add(Calendar.DAY_OF_YEAR, 1); // 加一天
			Date nextEndTime = calendar.getTime();
			task.setEndTime(nextEndTime);
			//删除原有记录
			b=eventPlanTaskService.removeById(task.getId());
			if (b == false){
				break;
			}else {
				//新增task
				eventPlanTaskService.save(task);
			}
		}
		if (b == false){
			return false;
		}
		//处理work
		QueryWrapper<EventPlanWork> qwWork = new QueryWrapper<>();
		qwWork.eq("event_plan_id",id);
		List<EventPlanWork> works = eventPlanWorkService.list(qwWork);
		//处理数据
		for (EventPlanWork work:works){
			//判断work是否需要修改
			ZoneId zoneId = ZoneId.systemDefault();
			LocalDate begin = work.getBeginTime().toInstant().atZone(zoneId).toLocalDate();
			LocalDate end = work.getEndTime().toInstant().atZone(zoneId).toLocalDate();
			b = begin.isEqual(end);
			if (b == false){
				continue;
			}
			Calendar calendar = Calendar.getInstance(); // 获取当前日期
			calendar.setTime(work.getEndTime());
			calendar.add(Calendar.DAY_OF_YEAR, 1); // 加一天
			Date nextEndTime = calendar.getTime();
			work.setEndTime(nextEndTime);
			//删除原有记录
			b=eventPlanWorkService.removeById(work.getId());
			if (b == false){
				break;
			}else {
				//新增task
				eventPlanWorkService.save(work);
			}
		}
		if (b == false){
			return false;
		}
		return true;
	}

	/**
	 * 14天计划处理
	 */
	@ApiOperation("14天计划处理")
	@PreAuthorize("@ss.hasPermi('module:eventPlan:query')")
	@GetMapping("/twoWeek/{id}")
	public Boolean twoWeek(@NotNull(message = "主键不能为空") @PathVariable("id") Integer id) {
		//处理task
		//查询结果
		boolean b = false;
		QueryWrapper<EventPlanTask> qw = new QueryWrapper<>();
		qw.eq("event_plan_id",id);
		List<EventPlanTask> tasks = eventPlanTaskService.list(qw);
		//处理数据
		for (EventPlanTask task:tasks){
			//判断该计划是否已经为14天计划
			ZoneId zoneId = ZoneId.systemDefault();
			LocalDate begin = task.getBeginTime().toInstant().atZone(zoneId).toLocalDate();
			LocalDate end = task.getEndTime().toInstant().atZone(zoneId).toLocalDate();
			b = begin.isEqual(end);
			if (b == false){
				continue;
			}

			Calendar calendar = Calendar.getInstance(); // 获取当前结束日期
			calendar.setTime(task.getEndTime());
			calendar.add(Calendar.DAY_OF_YEAR, 14); // 加十四天
			Date nextEndTime = calendar.getTime();
			task.setEndTime(nextEndTime);
			//删除原有记录
			b=eventPlanTaskService.removeById(task.getId());
			if (b == false){
				break;
			}else {
				//新增task
				eventPlanTaskService.save(task);
			}
		}
		if (b == false){
			return false;
		}
		//处理work
		QueryWrapper<EventPlanWork> qwWork = new QueryWrapper<>();
		qwWork.eq("event_plan_id",id);
		List<EventPlanWork> works = eventPlanWorkService.list(qwWork);
		//处理数据
		for (EventPlanWork work:works){
			//判断work是否需要修改
			ZoneId zoneId = ZoneId.systemDefault();
			LocalDate begin = work.getBeginTime().toInstant().atZone(zoneId).toLocalDate();
			LocalDate end = work.getEndTime().toInstant().atZone(zoneId).toLocalDate();
			b = begin.isEqual(end);
			if (b == false){
				continue;
			}
			Calendar calendar = Calendar.getInstance(); // 获取当前日期
			calendar.setTime(work.getEndTime());
			calendar.add(Calendar.DAY_OF_YEAR, 14); // 加十四天
			Date nextEndTime = calendar.getTime();
			work.setEndTime(nextEndTime);
			//删除原有记录
			b=eventPlanWorkService.removeById(work.getId());
			if (b == false){
				break;
			}else {
				//新增task
				eventPlanWorkService.save(work);
			}
		}
		if (b == false){
			return false;
		}
		return true;
	}
	/**
	 * 周计划处理
	 */
	@ApiOperation("周计划处理")
	@PreAuthorize("@ss.hasPermi('module:eventPlan:query')")
	@PostMapping("/week")
	public Boolean week(@Validated(AddGroup.class) @RequestBody EventPlan eventPlan) {
		//处理task
		//查询结果
		boolean b = false;
		QueryWrapper<EventPlanTask> qw = new QueryWrapper<>();
		qw.eq("event_plan_id",eventPlan.getId());
		List<EventPlanTask> tasks = eventPlanTaskService.list(qw);
		//处理数据
		for (EventPlanTask task:tasks){
			//判断该计划是否已经为周计划
			ZoneId zoneId = ZoneId.systemDefault();
			LocalDate begin = task.getBeginTime().toInstant().atZone(zoneId).toLocalDate();
			LocalDate end = task.getEndTime().toInstant().atZone(zoneId).toLocalDate();
			b = begin.isEqual(end);
			if (b == false){
				continue;
			}

			Calendar calendar = Calendar.getInstance(); // 获取当前结束日期
			calendar.setTime(task.getEndTime());
			calendar.add(Calendar.DAY_OF_YEAR, eventPlan.getTime()); // 加几天
			Date nextEndTime = calendar.getTime();
			task.setEndTime(nextEndTime);
			//删除原有记录
			b=eventPlanTaskService.removeById(task.getId());
			if (b == false){
				break;
			}else {
				//新增task
				eventPlanTaskService.save(task);
			}
		}
		if (b == false){
			return false;
		}
		//处理work
		QueryWrapper<EventPlanWork> qwWork = new QueryWrapper<>();
		qwWork.eq("event_plan_id",eventPlan.getId());
		List<EventPlanWork> works = eventPlanWorkService.list(qwWork);
		//处理数据
		for (EventPlanWork work:works){
			//判断work是否需要修改
			ZoneId zoneId = ZoneId.systemDefault();
			LocalDate begin = work.getBeginTime().toInstant().atZone(zoneId).toLocalDate();
			LocalDate end = work.getEndTime().toInstant().atZone(zoneId).toLocalDate();
			b = begin.isEqual(end);
			if (b == false){
				continue;
			}
			Calendar calendar = Calendar.getInstance(); // 获取当前日期
			calendar.setTime(work.getEndTime());
			calendar.add(Calendar.DAY_OF_YEAR, eventPlan.getTime()); // 加几天
			Date nextEndTime = calendar.getTime();
			work.setEndTime(nextEndTime);
			//删除原有记录
			b=eventPlanWorkService.removeById(work.getId());
			if (b == false){
				break;
			}else {
				//新增task
				eventPlanWorkService.save(work);
			}
		}
		if (b == false){
			return false;
		}
		return true;
	}

//    /**
//     * 删除巡检巡更、保洁等 执行计划
//     */
//    @ApiOperation("删除巡检巡更、保洁等 执行计划")
//    @PreAuthorize("@ss.hasPermi('module:eventPlan:remove')")
//    @Log(title = "巡检巡更、保洁等 执行计划" , businessType = BusinessType.DELETE)
//    @DeleteMapping("/{ids}")
//    public AjaxResult<Void> remove(@NotEmpty(message = "主键不能为空")  @PathVariable Integer[] ids) {
//		for (Integer id : ids){
//			QueryWrapper<EventPlanTaskLeader> qwLeader = new QueryWrapper<>();
//			qwLeader.eq("event_plan_id",id);
//			List<EventPlanTaskLeader> leaderList = eventPlanTaskLeaderService.list(qwLeader);
//			for (EventPlanTaskLeader leader:leaderList){
//				eventPlanTaskLeaderService.removeById(leader.getId());
//			}
//			QueryWrapper<EventPlanTask> qw = new QueryWrapper<>();
//			qw.eq("event_plan_id",id);
//			List<EventPlanTask> taskList = eventPlanTaskService.list(qw);
//			for (EventPlanTask task:taskList){
//				if (task.getState()==0){
//					eventPlanTaskService.removeById(task.getId());
//				}
//			}
//			//删除所有相关任务状态
//			QueryWrapper<EventPlanWork> qw1 = new QueryWrapper<>();
//			qw1.eq("event_plan_id",id);
//			List<EventPlanWork> workList = eventPlanWorkService.list(qw1);
//			for (EventPlanWork work:workList){
//				if (work.getState()==0){
//					eventPlanWorkService.removeById(work.getId());
//				}
//			}
//			//删除相关任务详情
//			QueryWrapper<EventPlanTaskInfo> qw2 = new QueryWrapper<>();
//			qw2.eq("event_plan_id",id);
//			List<EventPlanTaskInfo> taskInfos = eventPlanTaskInfoService.list(qw2);
//			if (taskInfos.size()>0){
//				for (EventPlanTaskInfo taskInfo:taskInfos){
//					if (taskInfo.getState()==0){
//						eventPlanTaskInfoService.removeById(taskInfo.getId());
//					}
//				}
//			}
//		}
//        return toAjax(eventPlanService.removeByIds(Arrays.asList(ids)) ? 1 : 0);
//    }



	/**
	 * 数据损坏处理
	 */
	@ApiOperation("删除巡检巡更、保洁等 执行计划")
	@PreAuthorize("@ss.hasPermi('module:eventPlan:remove')")
	@Log(title = "巡检巡更、保洁等 执行计划" , businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
	public AjaxResult<Void> remove(@NotEmpty(message = "主键不能为空")  @PathVariable Integer[] ids) {
		for (Integer id : ids){
			QueryWrapper<EventPlanWork> qw = new QueryWrapper<>();
			qw.eq("event_plan_id",id);
			List<EventPlanWork> list = eventPlanWorkService.list(qw);
			if (list.size()>0){
				for (EventPlanWork work:list){
					QueryWrapper<EventPlanTask> taskQw = new QueryWrapper<>();
					taskQw.eq("work_id",work.getId());
					List<EventPlanTask> taskList = eventPlanTaskService.list(taskQw);
					if (taskList.size()>0){
						for (EventPlanTask task:taskList){
							eventPlanTaskService.removeById(task);
						}
						eventPlanWorkService.removeById(work);
					}
				}
			}
			eventPlanService.removeById(id);
		}
		return toAjax(1);
	}


	/**
	 * 删除处理
	 */
	@ApiOperation("删除巡检巡更、保洁等 执行计划")
	@PreAuthorize("@ss.hasPermi('module:eventPlan:remove')")
	@Log(title = "巡检巡更、保洁等 执行计划" , businessType = BusinessType.DELETE)
	@DeleteMapping("/delete/{ids}")
	public AjaxResult<Void> removePlan(@NotEmpty(message = "主键不能为空")  @PathVariable Integer[] ids) {
		for (Integer id : ids){
			EventPlan plan = eventPlanService.findById(id);
			if (plan.getIsDel()==0){
				QueryWrapper<EventPlanTask> qw = new QueryWrapper<>();
				qw.eq("event_plan_id",id);
				qw.ne("state",2);
				List<EventPlanTask> list = eventPlanTaskService.list(qw);
				if (list.size()>0){
					for (EventPlanTask task:list){
						task.setState(3);
						eventPlanTaskService.updateById(task);
					}
				}
				plan.setIsDel(1);
			}else {
				QueryWrapper<EventPlanTask> qw = new QueryWrapper<>();
				qw.eq("event_plan_id",id);
				qw.eq("state",3);
				List<EventPlanTask> list = eventPlanTaskService.list(qw);
				if (list.size()>0){
					for (EventPlanTask task:list){
						task.setState(0);
						eventPlanTaskService.updateById(task);
					}
				}
				plan.setIsDel(0);
			}
			eventPlanService.updateById(plan);
		}
		return toAjax(1);
	}

}


